'use strict';


var appServer = 'http://192.168.199.170:11116/content/sts';
var bucket;
var region;
var path;

var urllib = OSS.urllib;
var Buffer = OSS.Buffer;
var OSS = OSS.Wrapper;
var STS = OSS.STS;

// Play without STS. NOT SAFE! Because access key id/secret are
// exposed in web page.

// var client = new OSS({
//   region: 'oss-cn-hangzhou',
//   accessKeyId: '<access-key-id>',
//   accessKeySecret: '<access-key-secret>',
//   bucket: '<bucket-name>'
// });
//
// var applyTokenDo = function (func) {
//   return func(client);
// };

var getCookie = function (name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
}

var applyTokenDo = function (func) {
    var url = appServer;
    return urllib.request(url, {
        method: 'GET',
        headers: {
            'Authorization': getCookie("token")
        },
    }).then(function (result) {
        var creds = JSON.parse(result.data);
        var client = new OSS({
            region: creds.region,
            accessKeyId: creds.AccessKeyId,
            accessKeySecret: creds.AccessKeySecret,
            stsToken: creds.SecurityToken,
            bucket: creds.bucket
        });
        path = creds.path;
        bucket = creds.bucket;
        region = creds.region;

        return func(client);
    });
};

var progress = function (p) {
    return function (done) {
        var bar = document.getElementById('progress-bar');
        bar.style.width = Math.floor(p * 100) + '%';
        bar.innerHTML = Math.floor(p * 100) + '%';
        done();
    }
};

function generateUUID() { // Public Domain/MIT
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
        d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

var uploadFile = function (client) {
    var file = document.getElementById('file').files[0];
    var key = path + generateUUID();
    console.log(file.name + ' => ' + key);

    return client.multipartUpload(key, file, {
        progress: progress
    }).then(function (res) {
        console.log('upload success: %j', res);
        return listFiles(client);
    });
};


var listFiles = function (client) {
    var table = document.getElementById('list-files-table');
    console.log('list files');

    return client.list({
        'max-keys': 100,
        'prefix': path
    }).then(function (result) {
        var objects = result.objects.sort(function (a, b) {
            var ta = new Date(a.lastModified);
            var tb = new Date(b.lastModified);
            if (ta > tb) return -1;
            if (ta < tb) return 1;
            return 0;
        });

        var numRows = table.rows.length;
        for (var i = 1; i < numRows; i++) {
            table.deleteRow(table.rows.length - 1);
        }
        //http://mars-translation-bucket.oss-cn-shenzhen.aliyuncs.com/objectsdasdasd
        for (var i = 0; i < Math.min(3, objects.length); i++) {
            var row = table.insertRow(table.rows.length);
            row.insertCell(0).innerHTML = "<a href=" + "http://" + bucket + "." + region + ".aliyuncs.com/" + objects[i].name + ">" + objects[i].name + "";
            row.insertCell(1).innerHTML = objects[i].size;
            row.insertCell(2).innerHTML = objects[i].lastModified;
        }
    });
};

var downloadFile = function (client) {
    var object = document.getElementById('dl-object-key').value.trim();
    var filename = document.getElementById('dl-file-name').value.trim();
    console.log(object + ' => ' + filename);

    var result = client.signatureUrl(object, {
        response: {
            'content-disposition': 'attachment; filename="' + filename + '"'
        }
    });
    window.location = result;

    return result;
};

window.onload = function () {
    document.getElementById('file-button').onclick = function () {
        applyTokenDo(uploadFile);
    }


    document.getElementById('list-files-button').onclick = function () {
        applyTokenDo(listFiles);
    }


    applyTokenDo(listFiles);
};
